package com.jxdinfo.hussar.example.common.schedulingtask;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jxdinfo.hussar.example.common.schedulingtask.dao.MdWorkshopMapper;
import com.jxdinfo.hussar.example.common.schedulingtask.model.MdWorkshop;
import com.jxdinfo.hussar.example.common.schedulingtask.service.MdWorkshopService;
import com.jxdinfo.hussar.example.common.schedulingtask.vo.MdWorkshopVO;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Author QiaoBin
 * @Date 2024/3/20 17:47
 * @Description 车间表的定时任务
 */
@Component
@AllArgsConstructor
public class WorkShopScheduleTask {
    private static final Logger logger = LoggerFactory.getLogger(WorkShopScheduleTask.class);

    private MdWorkshopService mdWorkshopService;
    private MdWorkshopMapper mdWorkshopMapper;


    /**
     * @Author QiaoBin
     * @Date 2024/3/20 16:07
     * @Description 车间管理表的定时任务
     */
    @Scheduled(cron = "0 0 0 * * ?") // 每天的凌晨执行一次
    public void departmentTask(){
        logger.info("\n车间管理表-定时任务-开始执行");
        LocalDateTime nowTime = LocalDateTime.now();
        synchronized ("departmentTask"){
            logger.info("\n鲁银-开始查询md_workshop表中最大的同步时间");
            LocalDateTime scheduleDate = mdWorkshopMapper.selectMaxScheduleDate();
            logger.info("\n鲁银-结束查询md_workshop表中最大的同步时间，查询结果scheduleDate={}",scheduleDate);
            String scheduleDateString = "";
            if (scheduleDate != null) {
                scheduleDateString = scheduleDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            //查询创建时间大于定时任务时间，查询出来后把所有数据全部插进去
            logger.info("\n用友-车间管理表-开始查询CBO_Department表中创建时间大于任务时间的数据,查询参数任务执行时间scheduleDateString={}", scheduleDateString);
            List<MdWorkshopVO> mesBaseWorkshopMoreList = mdWorkshopMapper.selectMoreSchedule(scheduleDateString);
            logger.info("\n用友-车间管理表-结束查询CBO_Department表中创建时间大于任务时间的数据,查询结果mesBaseWorkshopMoreList={}，size={}", mesBaseWorkshopMoreList,mesBaseWorkshopMoreList.size());
            if (mesBaseWorkshopMoreList.size() > 0) {
                ArrayList<MdWorkshop> mdWorkshopList = new ArrayList<>();
                for (int i = 0; i < mesBaseWorkshopMoreList.size(); i++) {
                    logger.info("\n用友-车间管理表-当前循环次数i={}", i);
                    MdWorkshopVO mdWorkshopVO = mesBaseWorkshopMoreList.get(i);
                    MdWorkshop mdWorkshop = new MdWorkshop();
                    mdWorkshop.setWorkshopCode(mdWorkshopVO.getWorkshopCode());  // 车间编码
                    mdWorkshop.setWorkshopName(mdWorkshopVO.getWorkshopName());   // 车间名称
                    mdWorkshop.setWorkshopId(mdWorkshopVO.getWorkshopId());   // 主键
                    mdWorkshop.setEnableFlag(mdWorkshopVO.getEnableFlag());   // 是否启用
                    mdWorkshop.setErpWorkshopId(mdWorkshopVO.getWorkshopId());
                    mdWorkshop.setCreateBy(mdWorkshopVO.getCreateBy());
                    mdWorkshop.setCreateTime(mdWorkshopVO.getCreateTime());
                    mdWorkshop.setUpdateBy(mdWorkshopVO.getUpdateBy());
                    mdWorkshop.setUpdateTime(mdWorkshopVO.getUpdateTime());
                    mdWorkshop.setScheduleTime(nowTime);
                    logger.info("\n用友-车间管理表-开始向list中存入数据，数据mdWorkshop={},i={}", mdWorkshop,i);
                    mdWorkshopList.add(mdWorkshop);
                }
                logger.info("\n用友-车间管理表-开始向md_workshop表中插入数据，数据mdWorkshopList={}", mdWorkshopList);
                boolean b = mdWorkshopService.saveBatch(mdWorkshopList, 100);
                logger.info("\n用友-车间管理表-结束向md_workshop表中插入数据，插入结果b={}", b);
            }
            if (scheduleDate == null) {
                logger.info("\n用友-车间管理表-查询不到任务时间，说明一次也没有同步，之间原封不动的插入就行,也就不需要更新");
                return;
            }
            if (scheduleDate != null) {
                //查询更新时间大于定时任务时间，查询出来后把所有数据全部更新进去
                logger.info("\n用友-车间管理表-开始查询CBO_Department更新时间大于任务时间，参数scheduleDateString={}", scheduleDateString);
                List<MdWorkshopVO> updateMoreSchedule = mdWorkshopMapper.selectUpdateMoreSchedule(scheduleDateString);
                logger.info("\n用友-车间管理表-结束查询CBO_Department更新时间大于任务时间,查询结果updateMoreSchedule={},数量size={}", updateMoreSchedule, updateMoreSchedule.size());

                if (updateMoreSchedule == null || updateMoreSchedule.size() == 0) {
                    logger.info("\n用友-车间管理表-没有查询到更新时间大于任务时间的CBO_ItemMaster和子表CBO_InventoryInfo数据");
                    return;
                }
                // 转成map集合
                Map<Long, MdWorkshopVO> moMoUpdateMap = updateMoreSchedule.stream().collect(Collectors.toMap(MdWorkshopVO::getWorkshopId, t -> t));
                // 获取CBO_ItemMaster和子表CBO_InventoryInfo更新过的主键
                List<Long> masterIdList = updateMoreSchedule.stream().map(MdWorkshopVO::getWorkshopId).collect(Collectors.toList());
                logger.info("\n用友-车间管理表-CBO_ItemMaster和子表CBO_InventoryInfo更新时间大于任务时间的主键集合masterIdList={},size={}", masterIdList, masterIdList.size());
                // 根据momo的主键去order和orderline表中查询数据momo_id=主键的记录，重新设置值并更新进去
                logger.info("\n用友-车间管理表-开始查询md_workshop中dept_id=erp表主键的数据,参数masterIdList={}", masterIdList);
                QueryWrapper<MdWorkshop> mdWorkshopWrapper = new QueryWrapper<>();
                mdWorkshopWrapper.in("warehouse_id",masterIdList);
                mdWorkshopWrapper.eq("deleted_flag",0);
                List<MdWorkshop> moreUpdateList = mdWorkshopMapper.selectList(mdWorkshopWrapper);
                logger.info("\n用友-车间管理表-结束查询md_workshop中master_id=erp表中主键的数据,结果moreUpdateList={},size={}", moreUpdateList, moreUpdateList.size());
                if (moreUpdateList.size() > 0) {
                    ArrayList<MdWorkshop> updateBaseWorkshopList = new ArrayList<>();
                    for (int i = 0; i < moreUpdateList.size(); i++) {
                        logger.info("\n用友-车间管理表-当前更新时间大于任务时间，mes_base_item表更新，次数i={}", i);
                        MdWorkshop mdWorkshop = moreUpdateList.get(i);
                        Long currentMasterId = mdWorkshop.getWorkshopId();
                        MdWorkshopVO mdWorkshopVO = moMoUpdateMap.get(currentMasterId);
                        mdWorkshop.setWorkshopCode(mdWorkshopVO.getWorkshopCode());  // 料
                        mdWorkshop.setWorkshopName(mdWorkshopVO.getWorkshopName());   //
                        mdWorkshop.setEnableFlag(mdWorkshopVO.getEnableFlag());   //
                        mdWorkshop.setScheduleTime(nowTime);
                        mdWorkshop.setCreateBy(mdWorkshopVO.getCreateBy());
                        mdWorkshop.setCreateTime(mdWorkshopVO.getCreateTime());
                        mdWorkshop.setUpdateBy(mdWorkshopVO.getUpdateBy());
                        mdWorkshop.setUpdateTime(mdWorkshopVO.getUpdateTime());
                        logger.info("\n用友-车间管理表-向updateBaseWorkshopList中存储待要更新的物料产品表信息,mdWorkshop={}", mdWorkshop);
                        updateBaseWorkshopList.add(mdWorkshop);
                    }
                    logger.info("\n用友-车间管理表-开始更新md_workshop数据,列表updateBaseWorkshopList={}", updateBaseWorkshopList);
                    boolean u = mdWorkshopService.updateBatchById(updateBaseWorkshopList);
                    logger.info("\n用友-车间管理表-结束更新md_workshop数据,更新结果u={}", u);
                }
            }
        }
        logger.info("\n车间管理表-定时任务-结束执行");
    }
}
